﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Http;
using PrivateTracker.Service.Core;

namespace PrivateTracker.Service.Application;
/// <summary>
/// 用户管理
/// </summary>
public class UserManager : IUserManager, IScoped
{
    private readonly IRepository<SysUser> _sysUserRep; // 用户表仓储
    private readonly IHttpContextAccessor _httpContextAccessor;

    public long UserId
    {
        get => long.Parse(_httpContextAccessor.HttpContext.User.FindFirst(ClaimConst.CLAINM_USERID)?.Value);
    }

    public string Account
    {
        get => _httpContextAccessor.HttpContext.User.FindFirst(ClaimConst.CLAINM_ACCOUNT)?.Value;
    }

    public string NickName
    {
        get => _httpContextAccessor.HttpContext.User.FindFirst(ClaimConst.CLAINM_NICKNAME)?.Value;
    }
    public bool SuperAdmin
    {
        get => _httpContextAccessor.HttpContext.User.FindFirst(ClaimConst.CLAINM_ROLETYPE)?.Value == ((int)RoleTypeEnum.SUPER_MANAGER_GROUP).ToString();
    }

    public SysUser User
    {
        get => _sysUserRep.FirstOrDefault(u => u.Id == UserId, false);
    }

    public UserManager(IRepository<SysUser> sysUserRep,
                       IHttpContextAccessor httpContextAccessor)
    {
        _sysUserRep = sysUserRep;
        _httpContextAccessor = httpContextAccessor;
    }

    /// <summary>
    /// 获取用户信息
    /// </summary>
    /// <param name="userId"></param>
    /// <param name="tracking"></param>
    /// <returns></returns>
    public async Task<SysUser> CheckUserAsync(long userId, bool tracking = true)
    {
        var user = await _sysUserRep.FirstOrDefaultAsync(u => u.Id == userId, tracking);
        return user ?? throw Oops.Oh(ErrorCode.D1002);
    }
}